<template>
  <!-- 创建团队的时候选择团队内的成员 -->
  <div class="member">
    <el-dialog title="成员管理" v-model="dialogTransfer" width="900px" append-to-body :close-on-click-modal="false"
      @close="closeDialogTransferClick">
      <div class="transferBox">
        <div class="transfer_left" style="">
          <!-- 搜索 -->
          <div style="width:100%;">
            <div class="search_box">
              <el-input v-model="searchInput" style="width: 200px;" @keyup.enter.native="searchUserClick"
                placeholder="请输入名称"></el-input>
              <el-button :icon="Search" class="search_btn" @click="searchUserClick">搜索</el-button>
              <!-- 部门 -->
              <el-popover ref="sortPopoverRefs" placement="bottom"  width="240" trigger="click"
                popper-class="popper_class_box">
                <div class="deptBox">
                  <el-checkbox-group v-model="dimensionalityCheckList" @change="memberCheckChange">
                    <el-checkbox  v-for="(item, index) in dimensionalityList" :key="index" :label="item.value" :value="item.value">
                      {{ item.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
                <div slot="reference" class="sort_box">
                  <span>维度</span>
                  <i class="el-icon-arrow-down"></i>
                </div>
              </el-popover>
            </div>
            <!-- 左边表格 -->
            <div>
              <el-table ref="tableRef" :data="teamPeopleList" :row-key="getRowKey" v-loading="teamPeopleLoading"
                @select="handleSelection" @selection-change="teamPeopleRowDbClick">
                <el-table-column type="selection" width="55" :selectable="selectableUser"
                  :reserve-selection="true"></el-table-column>
                <el-table-column prop="objectName" label="昵称">
                  <template #default="scope">

                    <div class="table_NameBox">
                      <!-- <img v-if="scope.row.objectType == '3'" style="background: #3662EC;" src="@/assets/images/jues.png" alt="" />
                      <img v-if="scope.row.objectType == '2'" style="background: #FE4D4F;" src="@/assets/images/gwei.png" alt="" />
                      <img v-if="scope.row.objectType == '1'" style="background: #07b9b9;" src="@/assets/images/bumeng.png" alt="" /> -->
                      <div v-if="scope.row.objectType == '0'" class="avatar">
                        <div>{{ scope.row.objectName.slice(0, 1) }}</div>
                      </div>
                      <div class="table_Name">
                        <p>{{ scope.row.objectName }}</p>
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="objectTypeText" label="维度" width="">
                  <template #default="scope">
                    <span>{{ scope.row.objectTypeText }}</span>
                  </template>
                  <!-- <span #default="scope">{{ scope.row.objectTypeText }}</span> -->
                </el-table-column>
              </el-table>
            </div>
            <div style="margin-top: 5px;">
              <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="requestStr.page" :page-sizes="[10, 20, 30, 40]" :page-size="requestStr.size"
                layout="total,  prev, pager, next,sizes" :total="requestStr.total">
              </el-pagination>
            </div>
          </div>
        </div>

        <div class="dialog_right">
          <p class="dialog_right_title">已选择（{{ rightUserList.length }}）</p>
          <div class="members_selected">
            <el-tag v-for="tag in rightUserList" :key="tag.id" :closable="!tag.disabled"
              :type="tag.disabled ? 'info' : 'primary'" @close="deptDeletePersonClick(tag)">
              {{ tag.objectName }}
            </el-tag>
          </div>

        </div>
      </div>
      <div slot="footer" class="dialog-footer create_box">
        <el-button @click="closeDialogTransferClick">取 消</el-button>
        <el-button type="primary" @click="sureDialogTransferClick">确 定</el-button>
      </div>
      <el-dialog width="500px" title="添加成员" v-model="innerVisible" append-to-body custom-class="dialog_transfer_box"
        :close-on-click-modal="false">
        <el-table :data="powerList" style="width: 100%" height="300px">
          <el-table-column>
            <template #header>
              <span>成员列表</span>
            </template>
            <template #default="scope">
              <div class="table_NameBox">
                <!-- <img v-if="scope.row.objectType == '3'" style="background: #3662EC;" src="@/assets/images/jues.png" alt="" />
                <img v-if="scope.row.objectType == '2'" style="background: #FE4D4F;" src="@/assets/images/gwei.png" alt="" />
                <img v-if="scope.row.objectType == '1'" style="background: #07b9b9;" src="@/assets/images/bumeng.png" alt="" /> -->
                <div class="avatar" v-if="scope.row.objectType == '0'">
                  <div>{{ scope.row.objectName.slice(0, 1) }}</div>
                </div>
                <div class="table_Name">
                  <p>{{ scope.row.objectName }}</p>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column>
            <template #default="scope">
              <div class="temp_box">
                <div class="role_box">
                  <el-select v-model="scope.row.id" placeholder="请选择" class="select_box">
                    <el-option v-for="item in peopleRoleList" :key="item.id" :label="item.roleName" :value="item.id"
                      :disabled="item.rank == 1">
                      <template #default>
                        <div class="role_item_box">
                          <div class="name">
                            <span>{{ item.roleName }}</span>
                          </div>
                          <div class="describe">{{ item.remark }}</div>
                        </div>
                      </template>

                    </el-option>
                  </el-select>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer create_box">
          <el-button @click="innerVisible = false">取 消</el-button>
          <el-button type="primary" @click="onSubmit" :loading="onSubmitLoading">确 定</el-button>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue"
import { apiTeamGetInformation, apiTeamMemberQuery, apiTeamRelevanceRoleQuery } from "@/api/teamKnowdge/teamDocApi"
import teamRoleApi from "@/api/teamKnowdge/teamRoleApi"
import { Search } from '@element-plus/icons-vue'

const route = useRoute()

// Dialog visibility
const dialogTransfer = ref(false)

// Lists and loading states
const teamPeopleList = ref<any[]>([])
const teamPeopleLoading = ref(false)
const rightUserList = ref<any[]>([])

// Search input
const searchInput = ref("")

// Pagination for team people
const requestStr = reactive({
  page: 1,
  size: 10,
  total: 0,
})

// Departments and permissions
const deptDatas = ref<any[]>([])
const powerList = ref<any[]>([]) // 权限列表
const dimensionalityCheckList = ref<any[]>([]) // 维度选中
const tableRef = ref(null)
// People roles
const peopleRoleList = ref<any[]>([])

// Dialog visibility for assigning permissions
const innerVisible = ref(false)
const defaultRoleId = ref(null)

// Submit loading state
const onSubmitLoading = ref(false)

// Tree default properties
const defaultProps = reactive({
  children: "children",
  label: "name",
  isLeaf: "leaf",
})

// Selected departments
const deptIdArray = ref<any[]>([])

// Current file ID
const currentId = ref("")

// Role pagination
const roleRequestStr = reactive({
  page: 0,
  size: 10,
  total: 0,
})

// Dimensionality list
const dimensionalityList = ref([
  { value: "0", label: "用户" },
  { value: "1", label: "部门" },
  { value: "3", label: "角色" },
  { value: "2", label: "岗位" },
])

// Default role ID
const roleId = ref(null)

onMounted(() => {
  openRoleListClick()
  getRoleList()

})

const getRowKey = (row) => {
  return row.id
}
const openRoleListClick = async () => {
  const res = await apiTeamGetInformation({
    id: route.query.teamId
  })
  if (res.code == 200) {
    roleId.value = res.data.defaultRole
  }
}
const memberCheckChange = () => {
  requestStr.page = 1
  getTableData()
}
const getRoleList = async () => {
  teamRoleApi
    .apiTeamRoleQuery({
      teamId: route.query.teamId,
      page: roleRequestStr.page,
      size: roleRequestStr.size,
    }).then((res) => {
      peopleRoleList.value = res.data.rows
      roleRequestStr.total = res.data.total
    })
}
const getTableData = async () => {
  teamPeopleLoading.value = true
  dialogTransfer.value = true
  let params = {
    page: requestStr.page - 1,
    size: requestStr.size,
    teamId: route.query.teamId,
    deptIds: deptIdArray.value,
    objectType: dimensionalityCheckList.value,
    NickName: searchInput.value || ""
  }
  const res = await apiTeamMemberQuery(params)
  if (res.code == 200) {
    teamPeopleList.value = res.data.rows
    requestStr.total = res.data.total
    teamPeopleLoading.value = false
    teamPeopleList.value.map(item => {
      let objectTypeText
      switch (item.objectType) {
        case 0:
          objectTypeText = "用户"
          break
        case 1:
          objectTypeText = "部门"
          break
        case 2:
          objectTypeText = "岗位"
          break
        case 3:
          objectTypeText = "角色"
          break
        default:
          objectTypeText = "未知"
      }
      // 将新属性添加到对象中
      item.objectTypeText = objectTypeText
      return item
    })
  } else {
    ElMessage.error(res.msg)
    teamPeopleLoading.value = false
  }

}
const getRightUserList = async (id) => {
  const res = await apiTeamRelevanceRoleQuery({
    treeNodeId: id
  })
  if (res.code == 200) {
    rightUserList.value = res.data.rows
    rightUserList.value.forEach((item) => {
      item.disabled = true
    })
  }
}
const selectableUser = (row) => {
  let disabled = true
  rightUserList.value.map((item) => {
    if (row.objectId === item.objectId && row.objectType === item.objectType) {
      if (item.disabled) {
        disabled = false
      }
    }
  })
  return disabled
}
const searchUserClick = () => {
  getTableData()
}
const handleSelection = (selectionArr, item) => {
  const checkedVal = selectionArr.find((x) => x.objectId === item.objectId && x.objectType === item.objectType)
  let obj = {
    objectId: item.objectId,
    objectType: item.objectType,
    objectName: item.objectName,
    disabled: false
  }
  if (checkedVal) {
    rightUserList.value.push(obj)
  } else {
    rightUserList.value.splice(
      rightUserList.value.findIndex((x) => x.objectId === item.objectId && x.objectType === item.objectType),
      1
    )
  }
}
const teamPeopleRowDbClick = (row) => {
  if (rightUserList.value.findIndex((item) => item.id == row.id) == -1) {
    rightUserList.value = rightUserList.value.concat(row)
  }
}

// 关闭成员穿梭框
const closeDialogTransferClick = () => {
  dialogTransfer.value = false
  rightUserList.value = []
  deptIdArray.value = []
  searchInput.value = ""
  requestStr.page = 1
  requestStr.size = 10
  // this.$refs.table.clearSelection();
  tableRef.value.clearSelection()
}
// 删除穿梭框右边成员
const deptDeletePersonClick = (val) => {
  rightUserList.value.forEach((item, index) => {
    if (item.id == val.id) {
      rightUserList.value.splice(index, 1)
    }
  })
}
// 确定按钮
const sureDialogTransferClick = async () => {
  let res1 = await apiTeamGetInformation({
    id: route.query.teamId
  })
  if (res1.code == 200) {
    defaultRoleId.value = res1.data.defaultRole
  }
  let res = rightUserList.value.filter((item) => !item.disabled)
  if (res.length != 0 && rightUserList.value.length != 0) {
    innerVisible.value = true
    powerList.value = res
    powerList.value.map((item) => {
      if (defaultRoleId.value) {
        item.id = Number(defaultRoleId.value)
      } else {
        item.id = null
      }
    })
  } else {
    ElMessage.error("请选择成员")
  }
}
const onSubmit = () => {
  // this.$emit("confirmClick", this.powerList);
  emit("confirmClick", powerList.value)
  closeDialogTransferClick()
  innerVisible.value = false
}
const handleCurrentChange = (val) => {
  requestStr.page = val
  getTableData()
}
const handleSizeChange = (val) => {
  requestStr.size = val
  getTableData()
}
const emit = defineEmits(["confirmClick"])

defineExpose({
  getTableData,
  getRightUserList
})

</script>

<style scoped>
.el-select-dropdown__item {
  width: 270px;
  height: auto;
  line-height: 20px;
  /* color: #1f2329 !important; */
  padding-bottom: 5px;
  padding-top: 5px;
  white-space: normal !important;
  word-wrap: break-word !important;
  .name{
    font-size: 14px;
    font-weight: 700;
  }
  .describe{
    font-size: 12px;
    color: #999;
  }
}


.describe {
  font-size: 12px;
}
</style>

<style lang="scss" scoped>
:deep(.el-dialog) {
  max-width: 900px !important;
  min-width: 790px !important;
}

:deep(.el-dialog__body) {
  padding: 0 20px 20px;
}

:deep(.el-tabs) {
  margin-bottom: 0;
}

.transferBox {
  display: flex;
  justify-content: space-between;

  .transferGloab {
    height: 500px;
    border: 1px solid #f1f1f1;
    overflow-y: auto;
    overflow-x: auto;
    padding: 6px;
  }

  .transfer_left {
    @extend .transferGloab;
    width: 480px;
    min-width: 480px;
  }

  .transfer_right {
    @extend .transferGloab;
    width: 320px;
    min-width: 320px;
  }

  .transfer_Right_perm {
    width: 100%;

    :deep(.el-input__inner) {
      border: 0px !important;
    }
  }

  .transfer_left {
    display: flex;
    justify-content: space-between;

    .left_left {
      width: 260px;
      height: 100%;
    }

    .left_right {
      height: 100%;
      width: 200px;
      min-width: 40%;
      border-left: 1px solid #f1f1f1;

      div {
        padding: 8px;
      }
    }
  }

  // .transfer_right {
  //   // width: 30%;
  //   // min-width: 360px;
  //   // max-width: 55%;
  // }

  .icon_size {
    font-size: 15px;
  }

  .icon_user {
    color: #36a3f7;
  }

  .transfer_center {
    height: 400px;
    padding-top: 150px;
    text-align: center;
    font-size: 26px;
  }

  .closeColor {
    margin-top: 6px;
    font-size: 16px;
    cursor: pointer;
  }

  .closeColor:hover {
    color: #f56c6c;
  }
}

.create_box {
  display: flex;
  justify-content: flex-end;

  :deep(.el-button--text) {
    padding: 9px 15px;
    color: #aaa;
  }

  :deep(.el-button--text:hover) {
    color: #6698ff;
  }

  :deep(.el-button--primary) {
    background-color: #6698ff;
    border-color: #6698ff;
  }

  :deep(.el-button--primary:focus) {
    box-shadow: 0 2px 5px 1px rgba(102, 152, 255, 0.6);
  }

  :deep(.el-button--primary:hover) {
    box-shadow: 0 2px 5px 1px rgba(102, 152, 255, 0.6);
  }
}

.search_box {
  display: flex;
  align-items: center;

  .search_btn {
    margin-left: 5px;
  }
}

.deptBox {
  width: 100%;
  max-height: 400px;
  overflow: auto;
}

.sort_box {
  color: #999;
  font-size: 15px;
  cursor: pointer;
  border-radius: 4px;
  padding: 8px;
  transition: all 0.2s ease;
  margin-left: 5px;

  span {
    color: #666;
    font-size: 14px;
    margin-left: 5px;
  }

  &:hover {
    color: #6698ff !important;
    background: rgba(102, 152, 255, 0.1);

    span {
      color: #6698ff !important;
    }
  }
}

.table_NameBox {
  display: flex;
  align-items: center;

  .avatar {
    width: 24px;
    height: 24px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 12px;
    background-color: #56abfb;
    margin-right: 4px;

    div {
      margin-top: 2px;
      margin-left: 1px;
      // transform: scale(0.9, 0.9);
    }
  }

  img {
    padding: 2px;
    width: 22px;
    height: 22px;
    margin-right: 5px;
    border-radius: 15px;
  }

  .table_Name {
    margin-left: 5px;

    p {
      margin: 0;
    }

    span {
      color: #999;
    }

    .table_Name_span {
      color: black;
    }

    .table_Name_syz {
      border: 1px solid #83acff;
      padding: 4px 5px;
      border-radius: 5px;
      margin-left: 5px;
      color: #83acff;
    }
  }
}

.item_box {
  display: flex;
  align-items: center;

  .item_icon {
    width: 22px;
    height: 22px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 14px;
    margin-right: 3px;

    .span_text {
      display: inline-block;
      margin-top: 2px;
      transform: scale(0.9, 0.9);
    }
  }

  .span_name {
    font-size: 13px;
    color: #333333;
  }

  .dept_bg {
    background-color: #07b9b9;
  }
}

.m_r_b {
  margin-bottom: 7px;
  margin-right: 7px;
  background: rgba(216, 216, 216, 0.4);
  border-radius: 3px 3px 3px 3px;
  padding: 4px 6px;
}

// .el-tag {
//   background-color: #efefef;
//   border: none;
//   color: #333;
//   font-weight: bold;
//   display: flex;
//   align-items: center;

//   svg {
//     background-color: #07b9b9;
//     font-size: 18px;
//     margin-right: 3px;
//     color: #fff;
//     padding: 3px;
//   }

//   img {
//     padding: 2px;
//     width: 18px;
//     height: 18px;
//     margin-right: 3px;
//   }

//   .people {
//     width: 22px;
//     height: 22px;
//     border-radius: 11px;
//     display: flex;
//     align-items: center;
//     justify-content: center;
//     color: #fff;
//     font-size: 12px;
//     background-color: #56abfb;
//     margin-right: 3px;

//     .span_text {
//       display: inline-block;
//       margin-top: 2px;
//       transform: scale(0.9, 0.9);
//     }
//   }
// }

.dialog_right {
  width: 380px;
  padding-left: 8px;
}

.dialog_right_title {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #333;
}

.members_selected {
  display: flex;
  margin-top: 10px;
  flex-wrap: wrap;
  gap: 10px;
  font-weight: 700;
}

.dialog_right_box {
  display: flex;
  flex-wrap: wrap;
}

.people {
  width: 22px;
  height: 22px;
  border-radius: 11px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 12px;
  background-color: #56abfb;
  margin-right: 3px;

  .span_text {
    display: inline-block;
    margin-top: 2px;
    transform: scale(0.9, 0.9);
  }
}
</style>
